package com.nantai.jiafang.nantaijiafang.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nantai.jiafang.nantaijiafang.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import static android.content.ContentValues.TAG;


public class DownLoadActivity extends Activity {
//
    private static final String LOG_TAG = "DownLoadActivity";
    private static final int INSTALLMSG = 1;
    private static final int UPATEMSG = 2;
    private static final int TOINDEX = 3;
    //APK安装路径
    private String apkPath;
    private String downLoadPath;
    private ProgressBar pDialog;
    private TextView downLoadPercent;
    private TextView downLoadSize;
    private Button cancelButton;
    private Button installButton;
    private LinearLayout downloadSuccessLayout;
    private LinearLayout downloadingLayout;

    private String backActivity;

    private long count;
    private long totalLen;
    DownloadTask downloadTask;

    private boolean downLoadFlg = true;
    //下载完成标识
    private boolean completeFlg = false;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case INSTALLMSG:
                    completeFlg = true;
                    downLoadFlg = false;
                    installButton.setVisibility(View.VISIBLE);
                    downloadSuccessLayout.setVisibility(View.VISIBLE);
                    downloadingLayout.setVisibility(View.GONE);
                   // installApk(apkPath);
                    break;
                case UPATEMSG:
                    final String loadFileSize = String.format(
                            getResources().getString(R.string.str_update_vision_msg_6),
                            String.valueOf(count / 1024), String.valueOf(totalLen / 1024));
                    final int percent = (int)((count * 100) / totalLen);

                    pDialog.setProgress(percent);

                    downLoadSize.setText(loadFileSize);
                    downLoadPercent.setText(String.valueOf(percent) + "%");

//                    if (100 == percent) {
//
//                    }
                    break;
                case TOINDEX:
                	//无效的下载路径
                    Toast.makeText(DownLoadActivity.this, "无效的下载路径", Toast.LENGTH_LONG)
                    .show();
                	break;
                default:
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_downloading);
        intiViewId();
        DownLoadActivity.this.setFinishOnTouchOutside(false);
        if (apkPath==null || "".equals(apkPath)) {
            //apk未下载，开始下载
            Log.i(LOG_TAG, "apk未下载，开始下载 : " + downLoadPath);
            downloadTask = new DownloadTask();
            downloadTask.execute("");
        } else {
            //apk已下载，开始安装
            Log.i(LOG_TAG, "apk已下载，开始安装");
            installApk(apkPath);
        }
    }



    public void intiViewId(){
        apkPath = getIntent().getStringExtra("apkPath");
        downLoadPath = getIntent().getStringExtra("downLoadPath");
        pDialog = (ProgressBar)findViewById(R.id.download_progressbar);
        downLoadPercent = (TextView)findViewById(R.id.download_percent_text);
        downLoadSize = (TextView)findViewById(R.id.download_file_size_text);
        cancelButton = (Button)findViewById(R.id.download_cancel_btn);
        installButton = (Button)findViewById(R.id.install_btn);
        downloadSuccessLayout = (LinearLayout) findViewById(R.id.download_success_layout);
        downloadingLayout = (LinearLayout) findViewById(R.id.downloading_layout);

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//            	downloadTask.cancel(false);
            	Log.i(LOG_TAG, "取消下载...");
            	finish();

            }
        });
        installButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	installApk(apkPath);
            }
        });
    }
    /**
     * 安装APK
     **/
    private void installApk(String apkFilePath) {
        Log.e(TAG, getApplicationContext().getPackageName()+"installApk:__________________________________________ " );
        Log.e(TAG, this.getPackageName()+"installApk:__________________________________________ " );
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+".fileprovider", new File(apkFilePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        }else {
            intent.setDataAndType(Uri.fromFile(new File(apkFilePath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
           startActivity(intent);
        }
    }
    private class DownloadTask extends AsyncTask<String, String, Integer> {

        @Override
        protected Integer doInBackground(String... params) {
            conn();
            return null;
        }

    }
    @SuppressLint("NewApi")
    public void conn() {
        Log.i(LOG_TAG, "连接下载地址准备下载： " + downLoadPath);
        final HttpGet get = new HttpGet(downLoadPath);
        final String sdcardState = Environment.getExternalStorageState();
        Log.i(LOG_TAG, "sdcard的状态：" + sdcardState);
        final DefaultHttpClient client = new DefaultHttpClient();

        try {
            final HttpResponse response = client.execute(get);
            Log.i(LOG_TAG, "response：" + response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200) {
                //得到体
                final HttpEntity entity = response.getEntity();
                final String tempFile = downLoadPath.substring(downLoadPath.lastIndexOf("/") + 1);
                Log.i(LOG_TAG, "tempFile = tempFile");

                if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
                    apkPath = Environment.getExternalStorageDirectory() + "/" + tempFile;
                    Log.i(LOG_TAG, "apkPath = " + apkPath);
                } else {
                    apkPath = getDir("apk",
                            MODE_APPEND | MODE_PRIVATE | MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE)
                            .getAbsolutePath() + "/" + tempFile;
                    Log.i(LOG_TAG, "apkPath = " + apkPath);

                    final String[] command = {"chmod", "777", apkPath,};
                    final ProcessBuilder builder = new ProcessBuilder(command);
                    builder.start();
                }
                final InputStream in = entity.getContent();
                totalLen = entity.getContentLength();
                Log.i(LOG_TAG, "totalLen = " + totalLen);

                if (in != null) {
                    final File file = new File(apkPath);

                    if (!file.exists()) {
                        file.createNewFile();
                    }else {
                        file.delete();
                        file.createNewFile();
                    }
                    final FileOutputStream out = new FileOutputStream(file);
                    final byte[] b = new byte[1024];
                    int len = -1;
                    count=0;
                    while ((len = in.read(b)) != -1) {
                            count += len;
                            out.write(b, 0, len);
                            handler.sendEmptyMessage(UPATEMSG);
                    }

                        handler.sendEmptyMessage(INSTALLMSG);
                        in.close();
                        out.close();

                }
            } else {
            	handler.sendEmptyMessage(TOINDEX);
            }
        } catch (Exception e) {
        	Log.i(LOG_TAG, "连接异常");
        	handler.sendEmptyMessage(TOINDEX);
            e.printStackTrace();
        }
    }


}
